<script setup lang="ts">
import { defineProps, ref, watch } from "vue"
import {
  FormInst,
  UploadFileInfo,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NUpload,
  // useMessage,
} from "naive-ui"
import { getOssApi } from "@api/index"

const props = defineProps<{
  showModal: boolean
  modalSubmit: (data: any) => void
  modalClose: () => void
  editConfig: any
}>()

const formRef = ref<FormInst | null>(null)
const ossConfig: any = ref({})
// const message = useMessage()
const fileList = ref<UploadFileInfo[]>([])
const formValue = ref({
  imgurl: "",
  clickhref: "",
})
const rules = {
  imgurl: {
    required: true,
    message: "请上传图片",
  },
  clickhref: {
    required: true,
    message: "请输入分类名称",
  },
}
//弹窗确认
const modalOnOk = () => {
  formRef.value?.validate(errors => {
    if (!errors) {
      if (props.editConfig.isEdit) {
        props.modalSubmit({ id: props.editConfig.echoData.id, ...formValue.value })
      } else {
        props.modalSubmit(formValue.value)
      }
    } else {
      console.log(errors)
    }
  })
}
//弹窗关闭
const modalCancel = () => {
  props.modalClose()
  formValue.value = {
    imgurl: "",
    clickhref: "",
  }
  fileList.value = []
}
// 校验图片的比例
// const checkScale = (img: any) => {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader()
//     reader.readAsDataURL(img)
//     reader.addEventListener('load', () => {
//       const url = reader.result
//       // 加载图片获取图片真实宽度和高度
//       const image: any = new Image()
//       image.onload = function () {
//         const w = image.width
//         const h = image.height
//         if (w / h === 16 / 9) {
//           resolve(true)
//         } else {
//           message.error('请上传比例为16:9的封面图')
//           reject(false)
//         }
//       }
//       image.src = url
//     })
//   })
// }

// 上传图片前回调
const beforeUpload = async (file: any) => {
  file.file.name = Date.now().toString() + '.' + file.file.type.slice(6)
  ossConfig.value = await getOssApi({})
  // }
  return true
}
//上传图片时携带的数据
const dataReturn = (file: any) => {
  return {
    key: ossConfig.value.data.dir + file.file.name,
    OSSAccessKeyId: ossConfig.value.data.accessid,
    ...ossConfig.value.data,
    success_action_status: "200",
  }
}
//上传完成回调
const uploadFinish = (file: any) => {
  if (file.file.status === "finished") {
    formValue.value.imgurl = `${ossConfig.value.data.host}/${ossConfig.value.data.dir}${file.file.name}`
  }
}
//编辑轮播图片的监听回调
watch(
  () => props.editConfig,
  (newValue, oldValue) => {
    if (newValue.isEdit === true) {
      formValue.value = {
        clickhref: newValue.echoData?.clickhref,
        imgurl: newValue.echoData?.imgurl,
      }
      fileList.value = [
        {
          id: newValue.echoData?.cateId,
          name: newValue.echoData?.clickhref,
          status: "finished",
          url: newValue.echoData?.imgurl,
        },
      ]
    }
  },
  {
    deep: true,
  }
)
</script>

<template>
  <div class="modal">
    <n-modal :show="props.showModal" preset="dialog" :title="props.editConfig.isEdit ? '编辑轮播项' : '新增轮播项'"
      positive-text="确认" negative-text="取消" @positive-click="modalOnOk" @negative-click="modalCancel" :show-icon="false"
      :on-close="modalCancel" :on-mask-click="modalCancel">
      <n-form ref="formRef" label-placement="left" :model="formValue" :rules="rules">
        <n-form-item label="图片:" path="imgurl">
          <n-upload :max="1" accept=".png,.jpg" :action="ossConfig?.data?.host" list-type="image-card"
            v-model:value="formValue.imgurl" :on-before-upload="beforeUpload" :data="dataReturn" :on-finish="uploadFinish"
            :default-file-list="fileList" />
        </n-form-item>
        <n-form-item label="跳转链接:" path="clickhref">
          <n-input class="form_item" v-model:value="formValue.clickhref" placeholder="请输入跳转链接" />
        </n-form-item>
      </n-form>
    </n-modal>
  </div>
</template>

<style lang="scss" scoped>
.form_item {
  width: 180px;
}
</style>
